package com.up.stores.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.up.stores.entity.Admin;
import com.up.stores.entity.User;
import com.up.stores.mapper.AdminMapper;
import com.up.stores.mapper.UserMapper;
import com.up.stores.service.IBaseUserService;
import com.up.stores.service.ex.*;
import com.up.stores.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;

@Service
public class BaseUserServiceImpl implements IBaseUserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AdminMapper adminMapper;
    /**
     * 注册
     * 异常的抛出还没有实现
     * @param
     */
    @Override
    public void reg(String realName, String username, String password, String password2, String phone, String email){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",username);
        User result=userMapper.selectOne(queryWrapper);

        if(result !=null){
            throw new UsernameDuplicateException("该用户名已存在");
        }

        //检测两次输入的密码是否相同
        if(!password.equals(password2)){
            throw new PasswordNotMatchException("两次输入的密码不同");
        }

        User user = new User();
        //密码加密处理实现——MD5算法加密，连续加载三次
        //盐值——随机字符串
        String oldPassword = password;
        //获取盐值并随机字符串盐值
        String salt = UUID.randomUUID().toString().toUpperCase();
        //不数据，盐值的记录
        user.setSalt(salt);
        //将密码和盐值作为整体做加密处理
        String md5Password = getMD5Password(oldPassword,salt);
        //将加密后的密码重新不全到user对象中
        user.setPassword(md5Password);
        //补全数据
        user.setRealName(realName);
        user.setUserName(username);
        user.setEmail(email);
        user.setPhone(phone);
        //补全数据：is_delete设置成0
        user.setIsDelete(0);
        //补全数据的四个日志字段信息
        user.setCreatedUser(user.getUserName());
        user.setModifiedUser(user.getUserName());
        Date date = new Date();
        user.setCreatedTime(date);
        user.setModifiedTime(date);

        //执行注册业务功能的实现（rows==1）
        Integer rows = userMapper.insert(user);
        if (rows != 1) {
            throw new InsertException("在用户注册过程中产生了未知的异常");
        }
    }

    /**
     * 登入
     * @param username
     * @param password
     * @return
     */
    @Override
    public User login(String username, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",username);
        User result=userMapper.selectOne(queryWrapper);
        if(result ==null)
        {
            throw new UserNotFoundException("账号不存在");
        }
        if(result.getIsDelete()==1){
            throw new UserIsdeleteException("账号已注销");
        }

        String salt=result.getSalt();
        String Md5password=getMD5Password(password,salt);

        if(!result.getPassword().equals(Md5password)){
            throw new PasswordNotMatchException("密码错误");
        }

        //重新封装
        User user =new User();
        user.setNorId(result.getNorId());
        user.setUserName(result.getUserName());
        user.setAvatar(result.getAvatar());
        return result;
    }

    /**
     * 改变密码
     * @param uid
     * @param username
     * @param oldPassword
     * @param newPassword
     */
    @Override
    public void changePassword(Integer uid, String username, String oldPassword, String newPassword, String newPassword2) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("nor_id",uid);
        User result = userMapper.selectOne(queryWrapper);

        if(result==null){
            //用户数据不存在
            throw new UserNotFoundException("用户不存在");
        }
        if(result.getIsDelete()==1){
            //用户已经注销
            throw new UserIsdeleteException("用户已注销");
        }

        String salt = result.getSalt();
        String Md5password = getMD5Password(oldPassword, salt);

        if(!result.getPassword().equals(Md5password)){
            //输入的原密码错误
            throw new PasswordNotMatchException("原密码错误");
        }

        if(!newPassword.equals(newPassword2)){
            throw new PasswordNotMatchException("两次输入的密码不同");
        }

        //重新组装数据
        String NewMd5Password = getMD5Password(newPassword,salt);
        Date now=new Date();
        User user = new User();
        user.setPassword(newPassword);
        user.setModifiedUser(result.getUserName());
        user.setModifiedTime(now);
        user.setPassword(NewMd5Password);
        //更新数据
        //把名字为rhb的用户年龄更新为18，其他属性不变
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("nor_id",result.getNorId());
        userMapper.update(user, updateWrapper);
        return;
    }


    @Override
    public UserVO getByUid(Integer uid) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("nor_id",uid);
        User result = userMapper.selectOne(queryWrapper);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(result,userVO);
        if(result.getAdmId()!=null){
            //填入adminName
            QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
            adminQueryWrapper.eq("adm_id", result.getAdmId());
            Admin admin = adminMapper.selectOne(adminQueryWrapper);
            userVO.setAdmName(admin.getAdminName());
        }
        return userVO;
    }

    /**
     *
     * 改变用户信息，内容暂时还没定下来
     * @param user
     */
    @Override
    public void changeInfo(User user,Integer uid) {
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("nor_id", uid);
        userMapper.update(user, updateWrapper);
    }

    @Override
    public void changeAvatar(Integer uid, String username, String avatar) {
        User user=userMapper.selectById(uid);
        if(user==null){
            throw new UserNotFoundException("用户数据不存在");
        }
        if(user.getIsDelete().equals(1)){
            throw new UserNotFoundException("用户数据不存在");
        }
        Date data=new Date();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("nor_id",uid);
        user.setAvatar(avatar);
        user.setModifiedTime(data);
        userMapper.update(user,queryWrapper);
    }

    //声明MD5加密处理
    private String getMD5Password(String password, String salt) {

        for (int i = 0; i < 3; i++) {
            //MD5加密算法调用，三次加密
            password = DigestUtils.md5DigestAsHex((salt + password + salt).getBytes()).toUpperCase();
        }
        return password;
    }
}


